package com.tangxz.sso.core.interceptors;

import com.tangxz.sso.core.conf.Conf;
import com.tangxz.sso.core.entity.User;
import com.tangxz.sso.core.utils.JedisUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: 唐小尊
 * @email: 1171702529@qq.com
 * @cate: 2021/07/11 20:49
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer requestURL = request.getRequestURL();//得到全路径，下面可能会重定向至，登录，之后需要回到当前
        String userid = "";
        if (request.getCookies() == null) {
            response.sendRedirect(Conf.SSO_SERVER_URL + Conf.SSO_LOGIN + "?" + Conf.REDIRECT_URL + "=" + requestURL);
            return false;
        }
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(Conf.SSO_USER)) {
                userid = cookie.getValue();
                break;
            }
        }
        if (userid == null || userid.isEmpty()) {
            response.sendRedirect(Conf.SSO_SERVER_URL + Conf.SSO_LOGIN + "?" + Conf.REDIRECT_URL + "=" + requestURL);
            return false;
        }
        User user = (User) JedisUtil.getObjectValue(userid);
        if (user == null) {
            response.sendRedirect(Conf.SSO_SERVER_URL + Conf.SSO_LOGIN + "?" + Conf.REDIRECT_URL + "=" + requestURL);
            return false;
        }
        //把用户信息保存在request中，留给你拦截的请求
        request.setAttribute(Conf.SSO_USER, user);
        return true;
    }
}
